import { queryDictMap } from '@/services/salaryManage/salaryCalculate';
import { isSuccess } from '@/utils/request';
import flatten from 'lodash/flatten';
import { getOrganizationList } from '@/services/Organization/orgmanage';
import { message } from 'antd';
import { convertTreeToArray } from '@/pages/SalaryManage/utils/treeUtil';
import { sessionStorageUtil } from './storageUtil';
import { SINGAPORE_CODE } from '../constant/countryRegion';

/**
 * 获得当前公司编码
 * @param currentUser 没传时从localStorage取值
 * @returns {string}
 */
const getCurrentCompanyCode = currentUser => {
    const user = currentUser || JSON.parse(localStorage.getItem('user'));
    return user?.firstOrgInfo?.firstCompanyCode;
};
/**
 * 获得当前用户国别编码
 * @param currentUser 没传时从localStorage取值
 * @returns {string}
 */
const getCurrentCountryCode = currentUser => {
    const user = currentUser || JSON.parse(localStorage.getItem('user'));
    const getCountryCodeFromCompany = () => {
        const userCompanyCode = user?.firstOrgInfo?.firstCompanyCode;
        const companyList = sessionStorageUtil.getItemInFinance('companySimpleList') || [];
        const countryItem = userCompanyCode && companyList.filter(item => item.organizationCode === userCompanyCode);
        return countryItem && countryItem[0] && countryItem[0].countryCode;
    };
    return user?.firstOrgInfo?.countryCode || user?.countryCode || getCountryCodeFromCompany();
};

/**
 * 获得当前机构国别编码
 * @param organizationCode 行政机构编码
 * @returns {string}
 */
const getCurrentOrgCountryCode = organizationCode => {
    const companyList = sessionStorageUtil.getItemInFinance('companySimpleList');
    const countryItem = companyList.filter(item => item.organizationCode === organizationCode);
    return countryItem && countryItem[0] && countryItem[0].countryCode;
};

/**
 * 判断是否为新加坡国别
 * @param organizationCode 行政机构编码
 * @returns {boolean}
 */
const isSingapore = organizationCode => SINGAPORE_CODE === getCurrentOrgCountryCode(organizationCode);

// 数字字典的缓存
const dictMap = {};
const loadingQueryTypes = {};

function resultFromPromise(resArray = [], typeList) {
    const result = {};

    resArray.forEach((res, index) => {
        if (res.hasOwnProperty('loaded')) {
            // 已经在缓存中的数据
            result[typeList[index]] = res.data;
        } else if (isSuccess(res)) {
            result[typeList[index]] = { ...res.data[typeList[index]] };
            dictMap[typeList[index]] = { ...res.data[typeList[index]] };
        }
    });

    return result;
}

/**
 * 获取数字字典的
 * @param confTypes 配置名集合
 * @returns {Promise<{}>}
 */
const obtainDictMap = function obtainDictMap(...confTypes) {
    const types = flatten(confTypes);
    // 待请求的类型
    const queryTypes = [];
    const typePromiseList = [];
    const typeList = [];

    types.forEach(type => {
        // 已经存在缓存中
        if (dictMap[type]) {
            typeList.push(type);
            typePromiseList.push(new Promise(resolve => resolve({ loaded: true, data: { ...dictMap[type] } })));
        } else if (loadingQueryTypes[type]) {
            // 已经在加载中的数据
            typeList.push(type);
            typePromiseList.push(loadingQueryTypes[type]);
        } else {
            // 还未加载的
            queryTypes.push(type);
        }
    });

    if (queryTypes.length === 0) {
        return new Promise((resolve, reject) => {
            Promise.all(typePromiseList)
                .then(resArray => {
                    resolve(resultFromPromise(resArray, typeList));
                })
                .catch(res => {
                    reject(res);
                });
        });
    }

    const queryPromise = queryDictMap(queryTypes);
    queryTypes.forEach(type => {
        loadingQueryTypes[type] = queryPromise;
    });

    return new Promise((resolve, reject) => {
        queryPromise
            .then(dictMapResponse => {
                if (isSuccess(dictMapResponse)) {
                    const result = {};
                    const keys = Object.keys(loadingQueryTypes);
                    keys.forEach(key => {
                        // 将正在加载的列表中移除
                        delete loadingQueryTypes[key];
                        // 加入到缓存
                        dictMap[key] = { ...dictMapResponse.data[key] };
                        // 加入到结果
                        result[key] = { ...dictMapResponse.data[key] };
                    });
                    if (typePromiseList.length === 0) {
                        resolve(result);
                    } else {
                        Promise.all(typePromiseList.values())
                            .then(resArray => {
                                resolve({ ...result, ...resultFromPromise(resArray, typeList) });
                            })
                            .catch(res => {
                                reject(res);
                            });
                    }
                } else {
                    reject(dictMapResponse);
                }
            })
            .catch(errorRes => {
                reject(errorRes);
            });
    });
};

/* 只允许输入中英文，数字，空格，_，-，()，首尾不能有空格 */
const COMMON_NAME = {
    REG: /^([A-Za-z0-9\u4e00-\u9fa5_\-()（）]{0,2}|[A-Za-z0-9\u4e00-\u9fa5_\-()（）][\sA-Za-z0-9\u4e00-\u9fa5_\-()（）]*[A-Za-z0-9\u4e00-\u9fa5_\-()（）])$/,
    MESSAGE: '只允许输入中英文，数字，空格，_，-，()，首尾不能有空格'
};

/**
 * 用以解决不能用PageRouter无法实现，用tab模板模拟相同效果的状况
 */
const pageTabProps = () => ({
    headStyle: { paddingLeft: 24, paddingRight: 24 },
    bodyStyle: { paddingLeft: 24, paddingRight: 24 }
});

/**
 * 抓取行政机构列表与返回默认行政机构，（注：默认取当前行政机构，不是当前行政机构返回第一个）
 * @param organizationCode
 * @returns {Promise}
 */
const fetchOrganizationListAndDefault = async organizationCode =>
    new Promise((resolve, reject) => {
        getOrganizationList({ organizationPermissions: 1, showTreeFlag: 1 })
            .then(response => {
                if (!isSuccess(response)) {
                    message.error(response.message);
                    reject(response);
                    return;
                }

                const orgList = convertTreeToArray(
                    response.data,
                    'children',
                    org => org.organizationType === 1 || org.organizationType === 2
                );

                let defaultSelectCode;
                let defaultSelectOrg;
                if (organizationCode) {
                    defaultSelectOrg = orgList.find(org => org.organizationCode === organizationCode);
                    defaultSelectCode = defaultSelectOrg?.organizationCode;
                } else {
                    // 默认取当前行政机构
                    const companyCode = getCurrentCompanyCode();
                    const currentCompanyOrg = orgList.find(org => org.organizationCode === companyCode);
                    // 当前行政机构不存在时取第1个
                    defaultSelectOrg = currentCompanyOrg || orgList?.[0];
                    defaultSelectCode = defaultSelectOrg?.organizationCode;
                }

                resolve({
                    organizationResponse: response,
                    organizationList: orgList,
                    defaultOrganization: defaultSelectOrg,
                    defaultOrganizationCode: defaultSelectCode
                });
            })
            .catch(response => {
                reject(response);
            });
    });
/**
 * 判断是否是字符串还是数组，字符串变成数组
 * @param {*} value
 * @param {string} separator 分割符
 */
export const makeArray = (value, separator) => {
    let newValue;

    if (!value) {
        newValue = [];
    } else if (Object.prototype.toString.call(value) !== '[Object Array]' && typeof value === 'string' && !!separator) {
        newValue = value.split(separator);
    } else if (Object.prototype.toString.call(value) !== '[Object Array]') {
        newValue = [value];
    }

    return newValue;
};
/**
 * 对象中属性值数组转化成,隔开的字符串
 * @param {object} value
 * @param {array | undefined} filterFields
 * @returns
 */
export const arrayToString = (value, filterFields) => {
    const newValue = { ...value };

    Object.keys(newValue).forEach(key => {
        const itemValue = newValue[key];
        if (!filterFields && Object.prototype.toString.call(itemValue) !== '[Object Array]') {
            newValue[key] = newValue[key].join(',');
        } else if (
            filterFields &&
            filterFields.indexOf(key) > -1 &&
            Object.prototype.toString.call(itemValue) !== '[Object Array]'
        ) {
            newValue[key] = newValue[key].join(',');
        }
    });

    return newValue;
};

/**
 * 获取随机一个数
 */
export const getRandomIndex = () => Math.random().toFixed(6) * 1000000;

export {
    getCurrentCompanyCode,
    getCurrentCountryCode,
    getCurrentOrgCountryCode,
    isSingapore,
    obtainDictMap,
    pageTabProps,
    fetchOrganizationListAndDefault,
    COMMON_NAME
};
